﻿/*
 * Utilisateur: Masy Freddy
 * Date: 27/10/2011
 * Heure: 7:49
 */
namespace SaverDvdLibrary
{
	using System;
	using System.Collections.Generic;
	using MetaVideoEditorEvolved.Helper;
	using System.IO;
	using System.Linq;
	using System.Xml.Serialization;

	[System.AddIn.AddIn("Dvd Library Saver",
	                    Version = "1.0.0.0",
	                    Description = "Dvd Library Saver",
	                    Publisher = "Masy Freddy")]
	public class DvdLibrary : MetaVideoEditorEvolved.AddIn.AddInViews.SaverView
	{
		private ConfigurationAddIn configurationAddIn;
		
		public DvdLibrary()
		{
			configurationAddIn = ConfigurationManager.Deserialize();
			
			if(configurationAddIn == null)
			{
				configurationAddIn = new ConfigurationAddIn()
				{
					InfoCacheFolder = string.Empty,
					TraceLevel = "Error"
				};
				
				ConfigurationManager.Serialize(configurationAddIn);
			}
			
			Tracer.TracerInstance.Level= string.IsNullOrEmpty(configurationAddIn.TraceLevel) ? TracerLevel.Error : (TracerLevel)Enum.Parse(typeof(TracerLevel), configurationAddIn.TraceLevel);
			Tracer.TracerInstance.FileName = "DvdLibrarySaver";
		}
		
		public override void SaveEpisode(string mediaLocation, MetaVideoEditorEvolved.AddIn.Entity.Episode episode)
		{
		}
		
		public override void SaveMovie(string mediaLocation, MetaVideoEditorEvolved.AddIn.Entity.Movie movie)
		{
			try
			{
				DirectoryInfo di = new DirectoryInfo(mediaLocation);
				
				if(File.Exists(mediaLocation))
				{
					di = di.Parent;
				}
				
				Disc disc = new Disc()
				{
					ID =  Guid.NewGuid().ToString(),
					Name = movie.Title
				};
				
				using (StreamWriter sw = new StreamWriter(Path.Combine(di.FullName, "mvee.dvdid.xml")))
				{
					new XmlSerializer(typeof(Disc)).Serialize(sw, disc);
				}
				
				if(!string.IsNullOrEmpty(configurationAddIn.InfoCacheFolder))
				{
					METADATA metadata = new METADATA()
					{
						DvdId = disc.ID,
						NeedsAttribution = true,
						MDRDVD =new METADATAMDRDVD()
						{
							MetadataExpires = DateTime.MinValue,
							version = 5.0M,
							dvdTitle = movie.Title,
							duration = movie.Duration.ToString(),
							title = new METADATAMDRDVDTitle()
							{
								titleTitle = movie.Title,
								synopsis = movie.Overview
							}
						}
					};
					
					string studio = string.Empty;
					
					foreach (var element in movie.Studios) {
						studio += element + ";";
					}
					
					if(!string.IsNullOrEmpty(studio))
					{
						studio = studio.Substring(0, studio.Length - 1);
					}
					
					metadata.MDRDVD.studio = studio;
					
					string leadPerformer = string.Empty;
					
					foreach (var element in movie.CastMembers.Where((o) => o.Activity.ToLower().Contains("act"))) {
						leadPerformer += element.FullName + ";";
					}
					
					if(!string.IsNullOrEmpty(leadPerformer))
					{
						leadPerformer = leadPerformer.Substring(0, leadPerformer.Length - 1);
					}
					
					metadata.MDRDVD.leadPerformer = leadPerformer;
					
					string directors = string.Empty;
					
					foreach (var element in movie.CastMembers.Where((o) => o.Activity.ToLower().Contains("dir"))) {
						directors += element.FullName + ";";
					}
					
					if(!string.IsNullOrEmpty(directors))
					{
						directors =  directors.Substring(0, directors.Length - 1);
					}
					
					metadata.MDRDVD.director = directors;
					
					metadata.MDRDVD.MPAARating = movie.MPAARating;
					
					if(movie.Year != 0)
					{
						metadata.MDRDVD.releaseDate = movie.Year + "01 01";
					}
					
					string genres = string.Empty;
					
					foreach (var element in movie.Genres) {
						genres += element + ";";
					}
					
					if(!string.IsNullOrEmpty(genres))
					{
						genres = genres.Substring(0, genres.Length - 1);
					}
					
					metadata.MDRDVD.genre = genres;
					
					using (StreamWriter sw = new StreamWriter(Path.Combine(configurationAddIn.InfoCacheFolder, disc.ID+ ".xml")))
					{
						new XmlSerializer(typeof(METADATA)).Serialize(sw, metadata);
					}
					
					SaveImage(mediaLocation, movie.Posters, movie.Backdrops, new List<Uri>());
				}
			}
			catch(Exception ex)
			{
				Tracer.TracerInstance.TraceError("Exception in the saver dvd library", ex);
				throw;
			}
		}
		
		public override void SaveSeason(string mediaLocation, MetaVideoEditorEvolved.AddIn.Entity.Season season)
		{
		}
		
		public override void SaveSerie(string mediaLocation, MetaVideoEditorEvolved.AddIn.Entity.Serie serie)
		{
		}
		
		public override void ShowOption()
		{
			new Option(configurationAddIn).ShowDialog();
		}
		
		public override bool HasOption()
		{
			return true;
		}
		
		private void SaveImage(string mediaLocation, List<Uri> poster, List<Uri> backdrops, List<Uri> banner)
		{
			if(File.Exists(Path.Combine(mediaLocation, "folder.jpg")))
			{
				File.Delete(Path.Combine(mediaLocation, "folder.jpg"));
			}
			
			foreach (var element in new DirectoryInfo(mediaLocation).GetFiles("backdrop*")) {
				File.Delete(element.FullName);
			}
			
			foreach (var posterElement in poster) {
				if(posterElement.AbsoluteUri.Contains("http"))
				{
					var posterImage = DownloadManager.RetrieveImage(posterElement.AbsoluteUri);
					
					if(posterImage != null)
					{
						posterImage.Save(Path.Combine(mediaLocation, "folder.jpg"));
						break;
					}
				}
				else
				{
					File.Copy(posterElement.LocalPath, Path.Combine(mediaLocation, "folder.jpg"), true);
				}
			}

			if(backdrops.Any())
			{
				for (int i = 0; i < backdrops.Count; i++) {
					string nameBackdropFile = i == 0 ? "backdrop.jpg" : string.Format("backdrop{0}.jpg", i);
					if(backdrops[i].AbsoluteUri.Contains("http"))
					{
						var backdropImage = DownloadManager.RetrieveImage(backdrops[i].AbsoluteUri);
						
						if(backdropImage != null)
						{
							backdropImage.Save(Path.Combine(mediaLocation, nameBackdropFile));
						}
					}
					else
					{
						File.Copy(backdrops[i].LocalPath, Path.Combine(mediaLocation, nameBackdropFile), true);
					}
				}
				
				if(banner.Any())
				{
					var bannerPath = banner.First().AbsoluteUri;
					
					if(bannerPath.Contains("http"))
					{
						var bannerImage = DownloadManager.RetrieveImage(bannerPath);
						
						if(bannerImage != null)
						{
							bannerImage.Save(Path.Combine(mediaLocation, "banner.jpg"));
						}
					}
					else
					{
						File.Copy(banner.First().LocalPath, Path.Combine(mediaLocation, "banner.jpg"), true);
					}
				}
			}
		}
	}
}